package com.jeesite.modules.announcement.web;

import com.jeesite.modules.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.announcement.entity.Announcement;
import com.jeesite.modules.announcement.service.AnnouncementService;

/**
 * announcementController
 * @author cele
 * @version 2025-08-20
 */
@Controller
@RequestMapping(value = "${adminPath}/announcement/announcement")
public class AnnouncementController extends BaseController {

	@Autowired
	private AnnouncementService announcementService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Announcement get(Long tid, boolean isNewRecord) {
		return announcementService.get(tid, isNewRecord);
	}

	/*
	根据id查找
	 */
	@GetMapping("{id}")
	public ResponseEntity<Announcement> getAnnouncement(@PathVariable Long id) {
		// 这里 @ModelAttribute 的 get 方法会自动被调用，但通常我们会直接用 service
		// 为了清晰，我们直接调用 service
		Announcement announcement = announcementService.get(id, false);
		if (announcement != null) {
			return ResponseEntity.ok(announcement);
		} else {
			return ResponseEntity.notFound().build();
		}
	}


	/**
	 * 查询列表
	 */

	@RequestMapping(value = {"list", ""})
	public String list(Announcement announcement, Model model) {
		model.addAttribute("announcement", announcement);
		return "modules/announcement/announcementList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequestMapping(value = "listData")
	@ResponseBody
	public Result<Page<Announcement>> listData(Announcement announcement, HttpServletRequest request, HttpServletResponse response) {
		announcement.setPage(new Page<>(request, response));
		Page<Announcement> page = announcementService.findPage(announcement);
		return Result.success(page);
	}

	/**
	 * 查看编辑表单
	 */
	@RequestMapping(value = "form")
	public String form(Announcement announcement, Model model) {
		model.addAttribute("announcement", announcement);
		return "modules/announcement/announcementForm";
	}

	/**
	 * 保存数据
	 */
	@PostMapping(value = "save")
	@ResponseBody
	public Result<String> save(@Validated Announcement announcement) {
		announcementService.save(announcement);
		return Result.success(renderResult(Global.TRUE, text("保存announcement成功！")));
	}
	
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public Result<String> delete(Announcement announcement) {
		announcementService.delete(announcement);
		return Result.success(renderResult(Global.TRUE, text("删除announcement成功！")));
	}

	
}